package com.green.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.green.model.manage.Person;
import com.green.service.common.ServiceContext;
import com.green.web.util.Constants;
import com.green.web.util.SessionHelper;

/**
 * 检查用户是否登录
 * 
 * @author fengwenjin
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private List<String> excludeUris;

	public void setExcludeUris(List<String> excludeUris) {
		this.excludeUris = excludeUris;
	}
	
	private static final Logger logger = Logger.getLogger(LoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.info("current url = " + request.getRequestURL() + "   current querystring = " + request.getQueryString());

		// IE浏览器 使用Chrome Frame加速
		response.addHeader("X-UA-Compatible", "chrome=1");

		Person person = (Person) SessionHelper.getAttribute(Constants.CURRENT_PERSON);
		ServiceContext.setLoginPerson(person);
		ServiceContext.setRequestIP(getIpAddr(request));
		
		String uri = request.getRequestURI().replaceAll(request.getContextPath(), "");
		if (excludeUris != null && excludeUris.contains(uri) || uri.lastIndexOf(".service") > 0 || uri.equals("/check") || uri.startsWith("/login") || uri.startsWith("/interface") || uri.startsWith("/f7")) {
			return true;
		}
		if (person == null) {
			((HttpServletResponse) response).sendRedirect(request.getContextPath() + "/login/overtime");
			return false;
		}
		SessionHelper.setAttribute(Constants.CURRENT_PERSON, person);
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	
	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
